import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ReadPacketHeader {
    private ReadPacket readPacket;
    private List<User> userList;

    private List<Double> minMoney = new ArrayList<>();

    public ReadPacketHeader() {
    }

    public ReadPacketHeader(ReadPacket readPacket, List<User> userList) {
        this.readPacket = readPacket;
        this.userList = userList;
    }

    public void handout() {

        // 1.把一个大红包拆分成多个小红包
        splitReadPacket();

        // 2.再把小红包分给不同的用户
        fanout();
    }

    // 把多个小红包分给不同的用户
    private void fanout() {
        for (int i = 0; i < minMoney.size(); i++) {
            userList.get(i).addMoney(minMoney.get(i));
        }
    }

    private void splitReadPacket() {
        double totalMoeny = readPacket.getMoney(); // 红包总金额
        int totalCount = readPacket.getCount(); // 红包数量
        Random random = new Random(); // 创建一个随机数类
        for (int i = 0; i < readPacket.getCount() - 1; i++) {
            double money = random.nextDouble() * (totalMoeny / totalCount) * 2;
            minMoney.add(round(money)); // 把每次的金额保存到集合里面
            totalMoeny -= money; // 本次的金额要从总金额中减去
            totalCount--; // 数量减一
        }
        minMoney.add(round(totalMoeny)); // 最后一份了
        System.out.println(minMoney);
    }

    // 小数点后保留两位
    public static double round(double x) {
        return Math.round(x * 100.0) / 100.0;
    }

    public void print() {
        double total = 0;
        for (User user : userList) {
            System.out.println(user);
            total += user.getBalance();
        }
        System.out.println("sum:" + total);
    }
}
